home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9216 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  69 lines

  1. Path: news.mel.aone.net.au!usenet
  2. From: clyde@hitech.com.au (Clyde Smith-Stubbs)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: read/write integers to files
  5. Date: Thu, 07 Mar 1996 10:47:08 GMT
  6. Organization: HI-TECH Software
  7. Message-ID: <313ebdba.694734775@news.bne.aone.net.au>
  8. References: <313EBF65.4E82@www.inia.net.au>
  9. Reply-To: clyde@hitech.com.au
  10. NNTP-Posting-Host: skyhawk.hitech.com.au
  11. X-Newsreader: Forte Agent .99d/32.182
  12.  
  13. On Thu, 07 Mar 1996 20:50:13 +1000, Jason Collins
  14. <jason@www.inia.net.au> wrote:
  15.  
  16. >My problem is that I'm trying to write a program that will read an integer from the file 
  17. >count.dat, increment the integer then write it back to count.dat.  I have provided the listing so 
  18. >that you can all tell me what I'm doing wrong.
  19.  
  20. Here's your problem:
  21.  
  22. >  filePtr=fopen("count.dat", "ab");
  23. >  fscanf(filePtr, "%d", &ctr);
  24.  
  25. You declared ctr as a char, but you're using a %d scanf format - you
  26. must pass a pointer to an int if you use %d. So make ctr an int and
  27. you should be right - I can't see any other obvious errors. However
  28. you could make it simpler: try this:
  29.  
  30. main()
  31. {
  32.     FILE *    fp;
  33.     int    x;
  34.  
  35.     fp = fopen("count.dat", "r+");
  36.     if(!fp) {
  37.         perror("count.dat");
  38.         exit(1);
  39.     }
  40.     x = 0;
  41.     fscanf(fp, "%d", &x);
  42.     x++;
  43.     rewind(fp);
  44.     fprintf(fp, "%d", x);
  45.     fclose(fp);
  46. }
  47.  
  48. Note the use of the "r+" format to open a file for reading and
  49. writing. The rewind() call allows you to switch from reading
  50. to writing.
  51.  
  52.  
  53. >  fclose(filePtr);
  54. >
  55. >  ctr++;
  56. >
  57. >  filePtr=fopen("count.dat", "wb");
  58. >  fprintf(filePtr, "%d", ctr);
  59. >  fclose(filePtr);
  60. >}
  61.  
  62. ----
  63.  Clyde Smith-Stubbs       | HI-TECH Software,       | Voice: +61 7 3300 5011
  64.  clyde@hitech.com.au      | P.O. Box 103, Alderley, | Fax:   +61 7 3300 5246
  65. http://www.hitech.com.au  | QLD, 4051, AUSTRALIA.   | BBS:   +61 7 3300 5235
  66. ----------------------------------------------------------------------------
  67. FREE! Download our shareware (FREE for noncommercial use) MS-DOS C Compiler!
  68.              Point your Web browser at http://www.hitech.com.au/
  69.